package com.gjy.config.java.apollo;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.model.ConfigChange;

import java.util.concurrent.TimeUnit;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-10-03 19:22:34
 */
public class ApolloDemo {
    // Apollo配置
    private static final String APP_ID = "SampleApp";
    private static final String APOLLO_META = "192.168.253.136:8080";

    public static void main(String[] args) {
        System.setProperty("app.id", APP_ID);
        System.setProperty("apollo.meta", "http://" + APOLLO_META);
        System.setProperty("apollo.cache-dir", "./config");
        System.setProperty("env", "dev");

        Config config = getConfig();

        String someKey = "timeout";
        String someDefaultValue = "someDefaultValueForTheKey";
        while (true) {
            String value = config.getProperty(someKey, someDefaultValue);
            System.out.println(value);
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    private static Config getConfig() {
        Config config = ConfigService.getAppConfig();
        config.addChangeListener(changeEvent -> {
            System.out.println("Changes for namespace " + changeEvent.getNamespace());
            for (String key : changeEvent.changedKeys()) {
                ConfigChange change = changeEvent.getChange(key);
                System.out.printf("Found change - key: %s, oldValue: %s, newValue: %s, changeType: %s%n", change.getPropertyName(), change.getOldValue(), change.getNewValue(), change.getChangeType());
            }
        });
        return config;
    }
}
